// 加权因子
const sfzhWi = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1 ]
// 身份证验证位值.10代表X
const sfzhValideCode = [ 1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2 ]

let isValidityBrithBy15IdCard = function (idCard15) {
  let year = idCard15.substring(6, 8)
  let month = idCard15.substring(8, 10)
  let day = idCard15.substring(10, 12)
  let tempDate = new Date(year, parseFloat(month) - 1, parseFloat(day))
  if (tempDate.getYear() !== parseFloat(year) ||
    tempDate.getMonth() !== parseFloat(month) - 1 ||
    tempDate.getDate() !== parseFloat(day)) {
    return false
  } else {
    return true
  }
}

let isValidityBrithBy18IdCard = function (idCard18) {
  let year = idCard18.substring(6, 10)
  let month = idCard18.substring(10, 12)
  let day = idCard18.substring(12, 14)
  let tempDate = new Date(year, parseFloat(month) - 1, parseFloat(day))
  // 这里用getFullYear()获取年份，避免千年虫问题
  if (tempDate.getFullYear() !== parseFloat(year) ||
    tempDate.getMonth() !== parseFloat(month) - 1 ||
    tempDate.getDate() !== parseFloat(day)) {
    return false
  } else {
    return true
  }
}

let isTrueValidateCodeBy18IdCard = function (idCard) {
  let sum = 0 // 声明加权求和变量
  if (idCard[17].toLowerCase() === 'x') {
    idCard[17] = 10// 将最后位为x的验证码替换为10方便后续操作
  }
  for (let i = 0; i < 17; i++) {
    sum += sfzhWi[i] * idCard[i]// 加权求和
  }
  let valCodePosition = sum % 11// 得到验证码所位置
  if (Number(idCard[17]) === sfzhValideCode[valCodePosition]) {
    return true
  } else {
    return false
  }
}

export default {
  checkMail (target) {
    let reg = /^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.){1,4}[a-z]{2,3}$/
    return reg.test(target)
  },
  checkPhoneNumber (target) {
    let reg = /(^0{0,1}1[3|4|5|6|7|8|9][0-9]{9}$)/
    return reg.test(target)
  },
  checkIdCard (idCard) {
    idCard = idCard.trim()
    if (idCard.length === 15) {
      return isValidityBrithBy15IdCard(idCard)
    } else if (idCard.length === 18) {
      let aIdCard = idCard.split('')// 得到身份证数组
      if (isValidityBrithBy18IdCard(idCard) && isTrueValidateCodeBy18IdCard(aIdCard)) {
        return true
      } else {
        return false
      }
    } else {
      return false
    }
  }
}
